/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.front.web.pay;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.pay.entity.log.EcPayLog;
import com.thinkgem.jeesite.modules.pay.entity.upop.EcOrgUpop;
import com.thinkgem.jeesite.modules.pay.sdk.AcpService;
import com.thinkgem.jeesite.modules.pay.sdk.LogUtil;
import com.thinkgem.jeesite.modules.pay.sdk.SDKConfig;
import com.thinkgem.jeesite.modules.pay.service.log.EcPayLogService;
import com.thinkgem.jeesite.modules.pay.service.upop.EcOrgUpopService;
import com.thinkgem.jeesite.modules.pay.util.PayUtil;
import com.thinkgem.jeesite.modules.pay.util.UPOPUtil.UPOPInstall;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * 退款Controller（FRONT）
 * 
 * @author Egan
 * @version 2016-12-15
 */
@Controller
@RequestMapping(value = "${frontPath}/front/refund")
public class RefundController extends BaseController {
	
	@Autowired
	ShopOrderService orderService;
	
	@Autowired 
	EcPayLogService ecPayLogService;
	
	@Autowired 
	EcOrgUpopService ecOrgUpopService;
	
	@RequestMapping(value = "order")
	public String order(ShopOrder order, Model model) {
		order = orderService.get(order);
		model.addAttribute("order", order);
		return "modules/refund/refund";
	}
	
	@RequestMapping(value = "forRefund")
	public void forRefund(HttpServletRequest req, HttpServletResponse resp, Model model) {
		try {
			String orderId = req.getParameter("orderId");
			String configPayId = req.getParameter("configPayId");
			String txnAmt = req.getParameter("txnAmt");
			EcOrgUpop upop = ecOrgUpopService.get(configPayId);
			EcPayLog log = new EcPayLog();
	        log.setOrgCode(upop.getMerchantId());
	        log.setMerChantid(upop.getMerchantId());
	        log.setCoNum(orderId);
	        EcPayLog ecPayLog = ecPayLogService.getEcPayLogByCoNumOrgCode(log);
	        
	        if (ecPayLog != null) {
	        	
	        	// 0：支付失败，1：支付成功，2支付结果不确定
	        	if ("0".equals(ecPayLog.getPayFlag())) {
	        		
	        	} else if ("1".equals(ecPayLog.getPayFlag())) {
	        		Map<String, String> data = UPOPInstall.installParamsForRefund(txnAmt, ecPayLog);
					/**请求参数设置完毕，以下对请求参数进行签名并发送http post请求，接收同步应答报文------------->**/
					//报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
					Map<String, String> reqData  = AcpService.sign(data,PayUtil.encoding_UTF8);
					//交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrls
					String url = SDKConfig.getConfig().getBackRequestUrl();
					//这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过
					Map<String, String> rspData = AcpService.post(reqData,url,PayUtil.encoding_UTF8);
					/**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
					//应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
					if(!rspData.isEmpty()){
						if(AcpService.validate(rspData, PayUtil.encoding_UTF8)){
							LogUtil.writeLog("验证签名成功");
							String respCode = rspData.get("respCode");
							if("00".equals(respCode)){
								//交易已受理，等待接收后台通知更新订单状态,也可以主动发起 查询交易确定交易状态。
								//TODO
							}else if("03".equals(respCode)|| 
									 "04".equals(respCode)||
									 "05".equals(respCode)){
								//后续需发起交易状态查询交易确定交易状态
								//TODO
							}else{
								//其他应答码为失败请排查原因
								//TODO
							}
						}else{
							LogUtil.writeErrorLog("验证签名失败");
							//TODO 检查验证签名失败的原因
						}
					}else{
						//未返回正确的http状态
						LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
					}
					
					String reqMessage = PayUtil.genHtmlResult(reqData);
					String rspMessage = PayUtil.genHtmlResult(rspData);
					resp.getWriter().write("</br>请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+"");
	        	} else if ("2".equals(ecPayLog.getPayFlag())) {
	        		
	        	}
	        }
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}